package com.luych.toolbox.common.service.base;

import com.luych.toolbox.common.feign.FeignInterface;
import com.luych.toolbox.common.feign.FeignParam;
import com.luych.toolbox.common.feign.FeignView;
import com.luych.toolbox.common.page.CommonPageParam;
import com.luych.toolbox.common.page.CommonPageResult;
import com.luych.toolbox.common.page.CommonSort;
import com.luych.toolbox.common.page.PageResult;
import org.springframework.util.StringUtils;

import java.util.UUID;

public abstract class BaseController<
        View extends FeignView,
        Param extends FeignParam,
        Entity extends BaseEntity> implements FeignInterface<View, Param> {

    private final BaseService<View, Param, Entity> baseService;

    public BaseController(BaseService<View, Param, Entity> baseService) {
        this.baseService = baseService;
    }

    @Override
    public CommonPageResult<View> page(long pageSize, long pageNumber, String sort, String order) {
        CommonPageParam commonPageParam = CommonPageParam.getInstance().setPageSize(pageSize).setPageNumber(pageNumber);
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            commonPageParam.addSort(CommonSort.getInstance().setSort(sort).setOrder(order));
        }
        PageResult<View> pageResult = baseService.page(commonPageParam);
        return CommonPageResult.getInstance(pageResult);
    }

    @Override
    public View get(String id) {
        return baseService.get(id).orElse(null);
    }

    private void setIdIfNull(Param param) {
        if (StringUtils.isEmpty(param.getId())) {
            param.setId(UUID.randomUUID().toString());
        }
    }

    @Override
    public View create(Param param) {
        this.setIdIfNull(param);
        return baseService.create(param);
    }

    @Override
    public View modify(String id, Param param) {
        param.setId(id);
        return baseService.modify(param);
    }

    @Override
    public void remove(String id) {
        baseService.remove(id);
    }

}
